package com.bt7274.service.impl;

import com.bt7274.exception.BusinessException;
import com.bt7274.mapper.AdminMapper;
import com.bt7274.pojo.Admin;
import com.bt7274.pojo.bo.AdminLoginBO;
import com.bt7274.pojo.vo.AdminInfoVO;
import com.bt7274.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @BelongsProject: bt7274-back
 * @BelongsPackage: com.bt7274.service.impl
 * @Author: Galland
 * @CreateTime: 2025-05-18
 * @Description: 管理员服务实现累类
 * @Version: 1.0
 */
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public AdminInfoVO login(AdminLoginBO adminLoginBO) {
        // 根据用户名查找管理员
        Admin admin = getByUsername(adminLoginBO.getUsername());
        if (admin == null) {
            throw new BusinessException("管理员账号不存在");
        }

        // 验证密码
        if (!verifyPassword(admin, adminLoginBO.getPassword())) {
            throw new BusinessException("密码错误");
        }

        // 转换为VO并返回
        log.info("管理员登录成功，ID: {}, 用户名: {}", admin.getId(), admin.getUsername());
        return convertToVO(admin);
    }

    @Override
    public AdminInfoVO getAdminInfo(String id) {
        Admin admin = adminMapper.selectById(id);
        if (admin == null) {
            throw new BusinessException("管理员不存在");
        }
        return convertToVO(admin);
    }

    @Override
    public Admin getByUsername(String username) {
        return adminMapper.selectByUsername(username);
    }

    @Override
    public boolean verifyPassword(Admin admin, String password) {
        return password.equals(admin.getPassword());
    }


    @Override
    public boolean checkAdminPermission(String adminId) {
        // 只要是管理员表中的用户，就有管理权限
        return adminMapper.selectById(adminId) != null;
    }

    /**
     * 转换为VO对象
     */
    private AdminInfoVO convertToVO(Admin admin) {
        AdminInfoVO vo = new AdminInfoVO();
        BeanUtils.copyProperties(admin, vo);
        return vo;
    }
}